<template>
  <el-container>
    <el-header>图书统计</el-header>
    <el-main>
      <el-row :gutter="20" style="margin-top: 20px">
        <!-- 饼图 -->
        <el-col :span="12">
          <div class="chart-container">
            <div id="pieChart" style="width: 100%; height: 400px"></div>
          </div>
        </el-col>

        <!-- 柱状图 -->
        <el-col :span="12">
          <div class="chart-container">
            <div id="barChart" style="width: 100%; height: 400px"></div>
          </div>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import { getCategoryData, getPriceData } from "@/api/book/index";

const pieChart = ref(null);
const barChart = ref(null);

// 初始化图表方法
const initCharts = async () => {
  try {
    const [categoryResp, priceResp] = await Promise.all([
      getCategoryData(),
      getPriceData(),
    ]);

    const categoryData = categoryResp.data?.data || [];
    const priceData = priceResp.data?.data || [];

    // 饼图配置
    let pieOption = {};
    if (!categoryData.length) {
      pieOption = {
        title: { text: "类别分布", left: "center" },
        graphic: {
          elements: [{
            type: 'text',
            shape: { x: 'center', y: 'center' },
            key: 'noDataText',
            style: { text: '暂无数据', fontSize: 20, fill: '#999' }
          }]
        }
      };
    } else {
      pieOption = {
        title: { text: "类别分布", subtext: "Dynamic Data", left: "center" },
        tooltip: { trigger: "item" },
        legend: { orient: "vertical", left: "left" },
        series: [
          {
            name: "图书数量",
            type: "pie",
            radius: "50%",
            data: categoryData,//后端数据
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
    }

    // 柱状图配置
    let barOption = {};
    const xAxisData = ["0-50", "50-100", "100-200", "200-500","500+"];
    if (!priceData.length) {
      barOption = {
        title: { text: "价格区间", left: "center" },
        graphic: {
          elements: [{
            type: 'text',
            shape: { x: 'center', y: 'center' },
            key: 'noDataText',
            style: { text: '暂无数据', fontSize: 20, fill: '#999' }
          }]
        }
      };
    } else {
      const seriesData = xAxisData.map((range, i) => ({
        name: range,
        value: priceData[i] || 0
      }));
      barOption = {
        tooltip: {},
        xAxis: {
          type: "category",
          data: xAxisData
        },
        yAxis: {},
        title: { text: "价格区间统计", left: "center" },
        series: [{
          name: "图书数量",
          type: "bar",
          data: seriesData//后端数据
        }]
      };
    }

    // 初始化或更新图表
    if (document.getElementById("pieChart")) {
      if (pieChart.value) pieChart.value.dispose(); // 先销毁旧实例
      pieChart.value = echarts.init(document.getElementById("pieChart"));
      pieChart.value.setOption(pieOption);
    }

    if (document.getElementById("barChart")) {
      if (barChart.value) barChart.value.dispose();
      barChart.value = echarts.init(document.getElementById("barChart"));
      barChart.value.setOption(barOption);
    }

  } catch (error) {
    console.error("加载图表数据失败:", error);

    // 统一显示“暂无数据”
    if (pieChart.value) pieChart.value.setOption({
      title: { text: "类别分布", left: "center" },
      graphic: {
        elements: [{
          type: 'text',
          shape: { x: 'center', y: 'center' },
          key: 'noDataText',
          style: { text: '暂无数据', fontSize: 20, fill: '#999' }
        }]
      }
    });

    if (barChart.value) barChart.value.setOption({
      title: { text: "价格区间统计", left: "center" },
      graphic: {
        elements: [{
          type: 'text',
          shape: { x: 'center', y: 'center' },
          key: 'noDataText',
          style: { text: '暂无数据', fontSize: 20, fill: '#999' }
        }]
      }
    });
  }
};

// 页面挂载后初始化图表
onMounted(() => {
  initCharts();
});

// 页面卸载前销毁图表，防止内存泄漏
onBeforeUnmount(() => {
  if (pieChart.value) {
    pieChart.value.dispose();
    pieChart.value = null;
  }
  if (barChart.value) {
    barChart.value.dispose();
    barChart.value = null;
  }
});
</script>

<style scoped>
.chart-container {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
}
</style>
